﻿using System.Configuration;
using System.Diagnostics;
using UtilZ.Dotnet.Ex.Base;

namespace UtilZ.Tool.Protect
{
    internal class Program
    {
        private static System.Threading.Mutex _globalMutex = null;
        static void Main(string[] args)
        {
            try
            {
                if (!ProcessEx.TryCreataSingleProcessMutex(true, "AE9F940E-DD71-4A15-B879-E148B3A68E8F", out _globalMutex))
                {
                    throw new Exception("主机保护程序已启动.");
                }



                string checkIntervalStr = System.Configuration.ConfigurationManager.AppSettings["checkInterval"];
                int checkInterval;
                if (!int.TryParse(checkIntervalStr, out checkInterval))
                {
                    checkInterval = 1000;
                }

                string protectAppPath = System.Configuration.ConfigurationManager.AppSettings["protectAppPath"];

                string noRespondingMillisecondsTimeoutStr = System.Configuration.ConfigurationManager.AppSettings["noRespondingMillisecondsTimeout"];
                int noRespondingMillisecondsTimeout;
                if (!int.TryParse(noRespondingMillisecondsTimeoutStr, out noRespondingMillisecondsTimeout))
                {
                    noRespondingMillisecondsTimeout = 5000;
                }

                string listenPortStr = System.Configuration.ConfigurationManager.AppSettings["listenPort"];
                int listenPort;
                if (!int.TryParse(listenPortStr, out listenPort))
                {
                    listenPort = 5230;
                }

                using (var protect = new ProcessMonitor(protectAppPath, checkInterval, noRespondingMillisecondsTimeout))
                {
                    protect.Start();

                    if (EnvironmentEx.IsWindowPlatform())
                    {
                        //如果是windows系统,则隐藏控制台窗口
                        ConsoleEx.HideCucrrentConsole();
                    }

                    Console.WriteLine("q exit");
                    ConsoleKeyInfo consoleKey;
                    while (true)
                    {
                        consoleKey = Console.ReadKey();
                        if (consoleKey.Key == ConsoleKey.Q)
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            ReleaseMutex();
        }

        private static void ReleaseMutex()
        {
            if (_globalMutex != null)
            {
                _globalMutex.ReleaseMutex();
                _globalMutex.Dispose();
            }
        }



    }
}